import json
import os
import shutil  
# import Capi
inpath = "./mid/config/"
outpath = "./mid/out/"

file_name = "virtualDevInit.dic"
def find_file(search_path, file_name):  
    """  
    在search_path路径下寻找文件file_name，并返回其完整路径（如果存在）  
    """  
    full_path = os.path.join(search_path, file_name)  
    if os.path.exists(full_path):  
        print(f"文件 {search_path}{file_name} 存在 ")  
        return full_path  
    else:  
        print(f"文件 {search_path}{file_name} 不存在 ")  
        return None  

def find_directories_in_path(path):  
    filelist = []
    # 确保传入的路径是以/结尾的，以便于路径拼接  
    if not path.endswith('/'):  
        path += '/'  
      
    # 获取指定路径下的所有文件和文件夹名  
    items = os.listdir(path)  
      
    # 遍历这些项，找出文件夹并打印它们的全路径  
    for item in items:  
        full_path = os.path.join(path, item)  
        # 使用os.path.isdir来检查是否是一个目录  
        if os.path.isdir(full_path):  
            filelist.append(full_path)
            # print(full_path)  
    

    return filelist

def find_matching_json_dic_pairs(directory):  
    # 用于存储符合条件的文件路径  
    matched_files = []  
  
    # 遍历目录下的所有文件和文件夹  
    for item in os.listdir(directory):  
        # 构建当前项的全路径  
        # print(item)
        # full_path = os.path.join(directory, item)  
        full_path = directory+"/"+item
        # 检查是否是以.json结尾的文件  
        if item.endswith('.json') and os.path.isfile(full_path):  
            # 去除.json扩展名，以获取基础文件名  
            base_name = os.path.splitext(item)[0]  
            # 构建对应的.dic文件的全路径  
            dic_path = os.path.join(directory, base_name + '.dic')  
              
            # 检查.dic文件是否存在  
            if os.path.isfile(dic_path):  
                # 如果存在，则打印两个文件的全路径，或者将它们添加到matched_files列表中  
                # print(f"Found matching .json and .dic files: {full_path} and {dic_path}")  
                # 如果你需要将路径添加到列表中而不是直接打印，可以使用以下方式  
                matched_files.append((full_path))
    return matched_files

# 从文件中解析json数据
def Parse_filedata_tojson(directory):
    """
    ### 从文件中解析json数据 <br>
    - directory : 文件路径 <br>
    """
    with open(directory, 'r', encoding='utf-8') as file:  
    # 读取并解析JSON数据  
        data = json.load(file) 
    return data

# 写入JSON文件
def write_json(file_path, data):
    with open(file_path, 'w', encoding="utf-8") as file:
        json.dump(data, file, ensure_ascii=False, indent=4)


# 重构virtualdevinit.dic 
def recon_virtualdevinit(json,savepath):
    """
    ### 重构virtualdevinit.dic 函数 <br>
    - json : 文件中读取后解析完毕的json数据 <br>
    - savepath : 重构后要保存的地址  <br>
    """
    Hashkey =0 
    mem = json

    virtualDevInit_count =0
    for i  in mem["virtualDevInit"]:
        # print(i)
        keys_count = 0
        for j in i["keys"]:
            mem["virtualDevInit"][virtualDevInit_count]["keys"][keys_count]["Hashkey"]=Hashkey
            Hashkey+=1
            keys_count+=1
            # print(j)
        virtualDevInit_count+=1
    write_json(savepath,mem)


def search_hascode(arrNo,cluNo,devNo,devDpName,devName,virtualdevdata):
    """
    ### 根据给出的条件从重构后的中间变量中获取对应的hascode -1未找到<br>
    - json : 原始文件中读取后解析完毕的json数据 <br>
    - virtualdevdata : 重构之后的中间变量json数据
    """
    for i in virtualdevdata["virtualDevInit"]:
        if arrNo == i["arrNo"] and cluNo == i["cluNo"] and devNo == i["devNo"] and devName == i["devName"] :
            for j in i["keys"]:
                if devDpName == j["key"]:
                    return j["Hashkey"]
    return -1 




def recon_jsonfile(json,virtualdevdata):
    """
    ### 重构json 函数 返回重构号的json <br>
    - json : 原始文件中读取后解析完毕的json数据 <br>
    - virtualdevdata : 重构之后的中间变量json数据
    """
    eve_count =0
    for i in json["eventAction"]:
        if "in" in i:
            if i["in"]["sourceType"] == "virtualDevFloat" or i["in"]["sourceType"] == "virtualDevInt" or i["in"]["sourceType"] == "vritualDevBool":
                file_arrNo=i["in"]["device"]["arrNo"]
                file_cluNo=i["in"]["device"]["cluNo"]
                file_devNo=i["in"]["device"]["devNo"]
                file_devDpName=i["in"]["paramKey"]
                file_devName=i["in"]["device"]["devName"]
                hashcode = search_hascode(file_arrNo,file_cluNo,file_devNo,file_devDpName,file_devName,virtualdevdata)
                if hashcode >=0 :
                    json["eventAction"][eve_count]["in"]["hashcode"]=hashcode
                    print(f"[in] {file_arrNo},{file_cluNo},{file_devNo},{file_devDpName},{file_devName} ||||hashcode 已找到 值为 {hashcode}")
                else :
                    print(f"[in] {file_arrNo},{file_cluNo},{file_devNo},{file_devDpName},{file_devName} ||||hashcode 未找到！！！值为 {hashcode}")
                    exit()



        eve_count+=1

    eve_count =0
    if "out" in json["eventAction"][-1]:
        # print("ERROR out存在")
        for i in json["eventAction"][-1]["out"]:
            if i["exec"]["sourceType"] == "virtualDevFloat" or i["exec"]["sourceType"] == "virtualDevInt" or i["exec"]["sourceType"] == "vritualDevBool":
                file_arrNo=i["exec"]["device"]["arrNo"]
                file_cluNo=i["exec"]["device"]["cluNo"]
                file_devNo=i["exec"]["device"]["devNo"]
                file_devDpName=i["exec"]["paramKey"]
                file_devName=i["exec"]["device"]["devName"]
                hashcode = search_hascode(file_arrNo,file_cluNo,file_devNo,file_devDpName,file_devName,virtualdevdata)
                if hashcode >=0 :
                    print(f"[out] {file_arrNo},{file_cluNo},{file_devNo},{file_devDpName},{file_devName} ||||hashcode 已找到 值为 {hashcode}")
                    json["eventAction"][-1]["out"][eve_count]["exec"]["hashcode"]=hashcode
                else :
                    print(f"{file_arrNo},{file_cluNo},{file_devNo},{file_devDpName},{file_devName} ||||hashcode 未找到！！！")
                    exit()
            eve_count+=1

    else:
        print("ERROR out不存在")
        return 0
    return json



def creat_newjson():
    # savejson_to_file(dict1,"./out/789.json")
    print("hello")
    virtualdev = find_file(inpath, file_name) #检查原始中间变量文件是否存在
    virtualdevdata = Parse_filedata_tojson(virtualdev) #读取为json
    os.makedirs(outpath,exist_ok=True)  
    write_json(f"{outpath}{file_name}",virtualdevdata)
    recon_virtualdevinit(virtualdevdata,f"{outpath}{file_name}") #重构后并保存

    virtualdev = find_file(outpath, file_name) #
    virtualdevdata = Parse_filedata_tojson(virtualdev) #重新将输出读取为json



    folderlist = find_directories_in_path(inpath) #读取配置文件下的所有文件夹
    print(folderlist)

    for i in folderlist:
        # os.mkdir("new_directory")  
        # i.split('/')[-1]
        # print( i.split('/')[-1])
        outfolder = outpath+i.split('/')[-1]
        os.makedirs(outfolder,exist_ok=True)  
        # os.mkdir(f"{outpath}{i.split('/')[-1]}",exist_ok=True) 
        filelist = []
        filelist = find_matching_json_dic_pairs(i)
        for j in filelist:
            print(j)
            item = Parse_filedata_tojson(j)
            outfile = outfolder+"/"+j.split('/')[-1]
        
            dicfile = j.rsplit('.', 1)[0] + ".dic"
            shutil.copy2(dicfile, outfile.rsplit('.', 1)[0] + ".dic") 
            ret = recon_jsonfile(item,virtualdevdata)
            write_json(outfile,ret)
            
            # print(ret)
            
    virtualdevdata_size = 0
    for i  in virtualdevdata["virtualDevInit"]:
        # print(i)
        for j in i["keys"]:
            # print(j)
            virtualdevdata_size=virtualdevdata_size+1

    print(f"运行完毕 中间变量个数为{virtualdevdata_size}")



  
if __name__ == '__main__':  
    creat_newjson()


# virtualdevdata123 = Parse_filedata_tojson(f"{outpath}{file_name}")
# for i  in virtualdevdata123["virtualDevInit"]:
#     # print(i)
#     cluNo = i["cluNo"]
#     arrNo = i["arrNo"]
#     devNo = i["devNo"]
#     for j in i["keys"]:
#         key = j["key"]
#         print(j)



# # savejson_to_file(data1231,"./out/123.json")
# folderlist = find_directories_in_path(inpath)
# # print(filelist)
# filelist = []
# file_count = 0


# print(filelist[0][0])

# filejson = Parse_filedata_tojson(filelist[0][0])
# print(filejson["eventAction"][-1]["out"][0]["exec"]["sourceType"])

# recon_virtualdevinit(virtualdevdata,"./out/123.json")
# with open(virtualdev, 'r', encoding='utf-8') as file:  
#     # 读取并解析JSON数据  
#     virtualdevdata = json.load(file)  



